package com.atguigu.forkjoin;

import java.util.Arrays;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * 注释：
 *
 * @author chenjt
 * @date 2024/7/4 16:53
 */
public class Test {


    private static class MyTask extends RecursiveTask<Integer>{

        int[] innerSrc;

        public MyTask(int[] innerSrc){
            this.innerSrc = innerSrc;

        }

        @Override
        protected Integer compute() {
            // 最底层MyTask处理逻辑
            if(innerSrc.length == 1){
                return innerSrc[0];
            }else{

                int mid = innerSrc.length / 2;
                MyTask leftTask = new MyTask(Arrays.copyOf(innerSrc, mid));
                MyTask rightTask = new MyTask(Arrays.copyOfRange(innerSrc, mid,innerSrc.length));
                invokeAll(leftTask,rightTask);

                // 中间层的 leftTask 和 rightTask 的处理逻辑（非顶层和底层）
                return leftTask.join() > rightTask.join() ? leftTask.join() : rightTask.join();
            }

        }

        /*@Override
        protected Integer compute() {
            if(innerSrc.length <= 2){
                if(innerSrc.length == 1){
                    return innerSrc[0];
                }else{
                    return innerSrc[0] > innerSrc[1] ? innerSrc[0] : innerSrc[1];
                }
            }else{

                int mid = innerSrc.length / 2;
                MyTask leftTask = new MyTask(Arrays.copyOf(innerSrc, mid));
                MyTask rightTask = new MyTask(Arrays.copyOfRange(innerSrc, mid,innerSrc.length));
                invokeAll(leftTask,rightTask);

                return leftTask.join() > rightTask.join() ? leftTask.join() : rightTask.join();
            }

        }*/
    }



    public static void main(String[] args) {
//        int[] src = {1,23,46,7,89,43,67};

        // 找到数组中的最大值
        int[] src = {1,23,46,7,891,43,67,12,56,79,100,57,83,56,92};
        ForkJoinPool pool = new ForkJoinPool();
        MyTask totalTask = new MyTask(src);

        pool.invoke(totalTask);
        System.out.println("最大值为：" + totalTask.join());

    }


}
